import React, { useState, useEffect } from 'react';
import { Layout, Card, Row, Col, Button, message, Modal, Typography, Tag, Input, Tabs } from 'antd';
import { WalletOutlined, ShoppingCartOutlined, BookOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons';
import { ethers } from 'ethers';

const { Header, Content } = Layout;
const { Title, Text } = Typography;
const { Search } = Input;

export default function BookStore() {
  const [activeTab, setActiveTab] = useState('home');
  const [books, setBooks] = useState([]);
  const [myBooks, setMyBooks] = useState([]);
  const [wallet, setWallet] = useState(null);
  const [loading, setLoading] = useState(false);
  const [purchaseModal, setPurchaseModal] = useState(false);
  const [selectedBook, setSelectedBook] = useState(null);

  // 模拟商城图书数据
  useEffect(() => {
    setBooks([
      {
        id: 1,
        isbn: '978-0123456789',
        title: '区块链技术指南',
        author: '张三',
        price: 0.1,
        available: 75,
        cover: 'https://via.placeholder.com/200x280/1890ff/white?text=区块链技术',
        description: '深入浅出地介绍区块链技术的原理和应用'
      },
      {
        id: 2,
        isbn: '978-9876543210',
        title: 'Web3开发实战',
        author: '李四',
        price: 0.15,
        available: 40,
        cover: 'https://via.placeholder.com/200x280/52c41a/white?text=Web3开发',
        description: '从零开始学习Web3开发，包含实战项目'
      },
      {
        id: 3,
        isbn: '978-1111111111',
        title: 'NFT艺术与投资',
        author: '王五',
        price: 0.08,
        available: 120,
        cover: 'https://via.placeholder.com/200x280/fa8c16/white?text=NFT艺术',
        description: 'NFT艺术品的创作、交易和投资指南'
      }
    ]);

    // 模拟用户已购买的图书
    setMyBooks([
      {
        id: 101,
        tokenCode: '978-0123456789_1_1',
        title: '区块链技术指南',
        author: '张三',
        purchaseDate: '2024-01-15',
        price: 0.1,
        cover: 'https://via.placeholder.com/200x280/1890ff/white?text=区块链技术'
      }
    ]);
  }, []);

  // 连接钱包
  const connectWallet = async () => {
    if (typeof window.ethereum !== 'undefined') {
      try {
        await window.ethereum.request({ method: 'eth_requestAccounts' });
        const provider = new ethers.providers.Web3Provider(window.ethereum);
        const signer = provider.getSigner();
        const address = await signer.getAddress();
        setWallet({ provider, signer, address });
        message.success('钱包连接成功！');
      } catch (error) {
        message.error('钱包连接失败: ' + error.message);
      }
    } else {
      message.error('请安装 MetaMask 钱包');
    }
  };

  // 购买图书
  const purchaseBook = async (book, quantity = 1) => {
    if (!wallet) {
      message.error('请先连接钱包');
      return;
    }

    setLoading(true);
    try {
      // 模拟购买成功
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 添加到我的图书
      const newBook = {
        id: Date.now(),
        tokenCode: `${book.isbn}_1_${Date.now()}`,
        title: book.title,
        author: book.author,
        purchaseDate: new Date().toISOString().split('T')[0],
        price: book.price,
        cover: book.cover
      };
      setMyBooks([...myBooks, newBook]);
      
      message.success(`成功购买《${book.title}》！`);
      setPurchaseModal(false);
      
      // 更新可用数量
      setBooks(books.map(b => 
        b.id === book.id 
          ? { ...b, available: b.available - quantity }
          : b
      ));
      
    } catch (error) {
      message.error('购买失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 显示购买模态框
  const showPurchaseModal = (book) => {
    setSelectedBook(book);
    setPurchaseModal(true);
  };

  // 首页内容
  const HomeContent = () => (
    <div>
      <div style={{ marginBottom: '30px' }}>
        <Title level={2}>热门图书</Title>
        <Text type="secondary">发现最新的区块链和Web3相关图书</Text>
      </div>

      <Row gutter={[24, 24]}>
        {books.map(book => (
          <Col xs={24} sm={12} md={8} lg={6} key={book.id}>
            <Card
              hoverable
              cover={
                <img 
                  alt={book.title} 
                  src={book.cover}
                  style={{ height: 280, objectFit: 'cover' }}
                />
              }
              actions={[
                <Button 
                  type="primary" 
                  icon={<ShoppingCartOutlined />}
                  onClick={() => showPurchaseModal(book)}
                  disabled={book.available === 0}
                >
                  {book.available > 0 ? '购买' : '售罄'}
                </Button>
              ]}
            >
              <Card.Meta
                title={book.title}
                description={
                  <div>
                    <Text type="secondary">作者: {book.author}</Text>
                    <br />
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      ISBN: {book.isbn}
                    </Text>
                    <br />
                    <Text style={{ margin: '8px 0', display: 'block' }}>
                      {book.description}
                    </Text>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '12px' }}>
                      <Text strong style={{ fontSize: '16px', color: '#1890ff' }}>
                        {book.price} ETH
                      </Text>
                      <Tag color={book.available > 0 ? 'green' : 'red'}>
                        剩余 {book.available}
                      </Tag>
                    </div>
                  </div>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );

  // 我的图书内容
  const MyBooksContent = () => (
    <div>
      <div style={{ marginBottom: '30px' }}>
        <Title level={2}>我的图书</Title>
        <Text type="secondary">您已购买的NFT图书收藏</Text>
      </div>

      {myBooks.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '60px 0' }}>
          <BookOutlined style={{ fontSize: '64px', color: '#d9d9d9' }} />
          <Title level={4} type="secondary">暂无图书</Title>
          <Text type="secondary">您还没有购买任何图书，去首页看看吧！</Text>
          <br />
          <Button type="primary" onClick={() => setActiveTab('home')} style={{ marginTop: '16px' }}>
            去购买图书
          </Button>
        </div>
      ) : (
        <Row gutter={[24, 24]}>
          {myBooks.map(book => (
            <Col xs={24} sm={12} md={8} lg={6} key={book.id}>
              <Card
                hoverable
                cover={
                  <img 
                    alt={book.title} 
                    src={book.cover}
                    style={{ height: 280, objectFit: 'cover' }}
                  />
                }
                actions={[
                  <Button type="primary">
                    阅读
                  </Button>,
                  <Button>
                    查看详情
                  </Button>
                ]}
              >
                <Card.Meta
                  title={book.title}
                  description={
                    <div>
                      <Text type="secondary">作者: {book.author}</Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        Token: {book.tokenCode}
                      </Text>
                      <br />
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        购买日期: {book.purchaseDate}
                      </Text>
                      <div style={{ marginTop: '12px' }}>
                        <Tag color="blue">已拥有</Tag>
                        <Text style={{ fontSize: '14px', color: '#1890ff' }}>
                          购买价格: {book.price} ETH
                        </Text>
                      </div>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>
      )}
    </div>
  );

  const tabItems = [
    {
      key: 'home',
      label: (
        <span>
          <BookOutlined />
          首页
        </span>
      ),
      children: <HomeContent />
    },
    {
      key: 'mybooks',
      label: (
        <span>
          <UserOutlined />
          我的图书
        </span>
      ),
      children: <MyBooksContent />
    }
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{ 
        background: '#fff', 
        padding: '0 50px', 
        borderBottom: '1px solid #f0f0f0',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <BookOutlined style={{ fontSize: '24px', color: '#1890ff', marginRight: '12px' }} />
          <Title level={3} style={{ margin: 0, color: '#1890ff' }}>
            图书NFT商城
          </Title>
        </div>
        
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <Search
            placeholder="搜索图书..."
            style={{ width: 300 }}
            prefix={<SearchOutlined />}
          />
          <Button 
            type="primary" 
            icon={<WalletOutlined />}
            onClick={connectWallet}
          >
            {wallet ? `${wallet.address.slice(0, 6)}...${wallet.address.slice(-4)}` : '连接钱包'}
          </Button>
        </div>
      </Header>

      <Content style={{ padding: '0 50px' }}>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
          size="large"
          style={{ marginTop: '24px' }}
        />
      </Content>

      {/* 购买确认模态框 */}
      <Modal
        title="购买确认"
        open={purchaseModal}
        onCancel={() => setPurchaseModal(false)}
        footer={[
          <Button key="cancel" onClick={() => setPurchaseModal(false)}>
            取消
          </Button>,
          <Button 
            key="purchase" 
            type="primary" 
            loading={loading}
            onClick={() => purchaseBook(selectedBook)}
          >
            确认购买
          </Button>
        ]}
      >
        {selectedBook && (
          <div>
            <Row gutter={16}>
              <Col span={8}>
                <img 
                  src={selectedBook.cover} 
                  alt={selectedBook.title}
                  style={{ width: '100%', borderRadius: '8px' }}
                />
              </Col>
              <Col span={16}>
                <Title level={4}>{selectedBook.title}</Title>
                <Text type="secondary">作者: {selectedBook.author}</Text>
                <br />
                <Text type="secondary">ISBN: {selectedBook.isbn}</Text>
                <br />
                <Text style={{ margin: '12px 0', display: 'block' }}>
                  {selectedBook.description}
                </Text>
                <div style={{ marginTop: '16px' }}>
                  <Text strong style={{ fontSize: '18px', color: '#1890ff' }}>
                    价格: {selectedBook.price} ETH
                  </Text>
                </div>
              </Col>
            </Row>
          </div>
        )}
      </Modal>
    </Layout>
  );
} 